package com.transcargo.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;

import com.transcargo.config.ConfigManager;
import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.geo.Country;
import com.transcargo.geo.GeoObjectNotFoundException;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;

public class Cache extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected ArrayList<String[]> list = null;
    protected Iterator<String[]> iter = null;
    protected Cookie[] cookies = null;
    protected db dbase = null;
    
	protected HashMap<String,String> ptypes = null;
	protected HashMap<String,String> curr = null;
	protected HashMap<String,String> type = null;
	protected HashMap<String,String> loads = null;
	protected int num_countries = 0;
	protected Country[] countries = null;
	
	private static Cache hInstance = null;
	private static Logger logger = Logger.getLogger(Cache.class);;
    
	public void init(ServletConfig config) throws ServletException {
		hInstance = this;
	    String prefix =  config.getServletContext().getRealPath("WEB-INF");
	    String file = "/log4j.properties";
        PropertyConfigurator.configure(prefix+file);

        
        logger.info("Initializing Cache...");
        dbase = new db();
        if (!dbase.init()) throw new ServletException("Failed to connect to DB: " + ConfigManager.getProperty("DB_URL"));
		ptypes = new HashMap<String,String>();
		curr = new HashMap<String,String>();
		type = new HashMap<String,String>();
		loads = new HashMap<String,String>();
		try {
			list = dbase.execute("SELECT id, name FROM payment_types");
			if (list != null) iter = list.iterator();
			System.out.println("Found " + list.size() + " payment types");
			while (iter.hasNext()) {
				String[] ctr = iter.next();
				ptypes.put(ctr[0],ctr[1]);				
			}
			list = dbase.execute("SELECT id, name FROM payment_currencies");
			if (list != null) iter = list.iterator();
			System.out.println("Found " + list.size() + " payment currencies");
			while (iter.hasNext()) {
				String[] ctr = iter.next();
				curr.put(ctr[0],ctr[1]);				
			}
			list = dbase.execute("SELECT id, name FROM transport_type");
			if (list != null) iter = list.iterator();
			System.out.println("Found " + list.size() + " transport types");
			while (iter.hasNext()) {
				String[] ctr = iter.next();
				type.put(ctr[0],ctr[1]);				
			}
			list = dbase.execute("SELECT id, name FROM transport_loading");
			if (list != null) iter = list.iterator();
			System.out.println("Found " + list.size() + " transport loadings");
			while (iter.hasNext()) {
				String[] ctr = iter.next();
				loads.put(ctr[0],ctr[1]);				
			}
			list = dbase.execute("SELECT id FROM countries");
			if (list != null) {
				iter = list.iterator();
				System.out.println("Found " + list.size() + " countries");
				num_countries = list.size();
				countries = new Country[num_countries];
				int i = 0;
				try {
					while (iter.hasNext()) {
						String ctr[] = iter.next();
						countries[i++] = new Country(Integer.parseInt(ctr[0]), true, dbase);
					}
				} catch (NumberFormatException e) {
					throw new ServletException(e.getMessage());
				} catch (GeoObjectNotFoundException e) {
					throw new ServletException(e.getMessage());
				}
			}
		} catch (dbException e) {
			throw new ServletException(e.getMessage());
		}
	}
	
	public static HashMap<String,String> getPaymentTypes() {
		return hInstance.ptypes;
	}
	public static HashMap<String,String> getCurrencies() {
		return hInstance.curr;
	}
	public static HashMap<String,String> getTransportTypes() {
		return hInstance.type;
	}
	public static HashMap<String,String> getTransportLoadings() {
		return hInstance.loads;
	}
	public static Country[] getCountries() {
		return hInstance.countries;
	}
	public static Country getCountry(int id) {
		for (int i = 0;i < hInstance.num_countries; i++) if (hInstance.countries[i].getId() == id) return hInstance.countries[i];
		return null;
	}
	public static Country getCountry(String name) {
		for (int i = 0;i < hInstance.num_countries; i++) if (hInstance.countries[i].getName().equals(name)) return hInstance.countries[i];
		return null;
	}
	public static Logger getLogger() {
		return logger;
	}
}

